<template>
  <HomepageMenu :menuList="menuList" style="height: 56px"></HomepageMenu>
  <div id="TaskTempletList">
    <Breadcrumb content="传输模版" />
    <el-container class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="传输模版">
          <Splitpanes>
            <Pane :size="(300 / conWidth) * 100">
              <vxe-button
                class="addRootBtn button-blue"
                type="text"
                icon="vxe-icon-add"
                content="新增根模块"
                @click="appendPPage()"
              ></vxe-button>

              <el-scrollbar style="height: calc(100% - 52px)">
                <div class="sampleType">
                  <el-scrollbar>
                    <el-tree
                      ref="leftTree"
                      :data="taskPageTree"
                      v-loading="showTreeLoading"
                      :props="defaultProps"
                      @node-click="handleNodeClick"
                      class="tools-tree"
                      node-key="id"
                      default-expand-all
                      highlight-current
                      :current-node-key="currentTreeId"
                    >
                      <template #default="{ data }">
                        <span>{{ data.name }}</span>
                        <div class="cunston-tree-code">
                          <span>
                            <!-- 新增  -->
                            <el-button
                              type="success"
                              class="cirBtn"
                              size="small"
                              icon="Plus"
                              circle
                              @click="appendTaskPage(data)"
                            ></el-button>
                            <!-- 编辑  -->
                            <el-button
                              type="warning"
                              class="cirBtn"
                              size="small"
                              icon="Edit"
                              circle
                              @click="editTaskPage(data)"
                            ></el-button>
                            <!-- 删除  -->
                            <el-button
                              type="info"
                              class="cirBtn"
                              size="small"
                              icon="Delete"
                              circle
                              @click="removeTaskPage(data)"
                            ></el-button>
                          </span>
                        </div>
                      </template>
                    </el-tree>
                  </el-scrollbar>
                </div>
              </el-scrollbar>

              <!-- 页面对话框 -->
              <el-dialog
                :title="titleType()"
                :show-close="false"
                v-model="showTaskPageDialog"
                append-to-body
                :close-on-click-modal="true"
                width="500px"
                style="height: 250px"
              >
                <el-form
                  ref="taskPageFormRef"
                  :rules="addRouteDialogRules"
                  :model="taskPageForm"
                  label-width="100px"
                  class="form-input-m"
                  inline-message
                >
                  <el-form-item prop="name" label="页面名称">
                    <el-input
                      type="text"
                      v-model="taskPageForm.name"
                      placeholder="请输入模块编号"
                    ></el-input>
                  </el-form-item>
                  <el-form-item prop="code" label="页面编号">
                    <el-input
                      type="text"
                      v-model="taskPageForm.code"
                      placeholder="请输入模块名称"
                      :disabled="taskPageForm.id ? true : false"
                      clearable
                    ></el-input>
                  </el-form-item>
                  <el-form-item prop="typeId" label="所属页面">
                    <el-select v-model="taskPageForm.typeId" placeholder="请选择">
                      <el-option
                        v-for="item in pageOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer flex right justify-end">
                  <el-button type="primary" @click="saveTaskPage(taskPageFormRef)">保存</el-button>
                  <el-button @click="closeTaskPageDialog(taskPageFormRef)">取消</el-button>
                </div>
              </el-dialog>
            </Pane>

            <Pane :size="(1100 / conWidth) * 100">
              <div class="models">
                <vxe-button
                  class="addModels button-blue"
                  type="text"
                  icon="vxe-icon-add"
                  content="新增模版"
                  @click="addFormList()"
                ></vxe-button>

                <el-scrollbar style="height: calc(100% - 54px)">
                  <div class="MiddleContent" v-if="taskTempletList.length > 0">
                    <div v-for="(item, index) in taskTempletList" :key="index" class="cardBox">
                      <el-card class="box-card">
                        <el-tabs type="border-card" @tab-click="testAdd(item, index)">
                          <el-tab-pane label="设计模式">
                            <div class="card_header">
                              <span>数据传输模板 {{ index + 1 }}</span>
                              <div
                                class="dialogButtons flex right justify-end"
                                style="display: inline-block"
                              >
                                <el-button
                                  icon="Delete"
                                  @click="removeTaskTemplet(item)"
                                  class="delBtn button-red"
                                  >删除</el-button
                                >

                                <el-button
                                  icon="MessageBox"
                                  @click="saveTemplet(index)"
                                  class="button-blue"
                                  >保存</el-button
                                >
                              </div>
                            </div>

                            <el-form
                              :ref="'form' + index"
                              :rules="modelDesignRules"
                              label-width="110px"
                              :model="templetForms[index]"
                              v-loading="modelsLoading"
                              class="form-input-l"
                              inline-message
                            >
                              <el-form-item label="任务标题" prop="title">
                                <el-input v-model="templetForms[index].title"></el-input>
                              </el-form-item>
                              <el-form-item label="任务编码" prop="code">
                                <el-input v-model="templetForms[index].code"></el-input>
                              </el-form-item>
                              <el-form-item label="任务类型" prop="type">
                                <el-input v-model="templetForms[index].type"></el-input>
                              </el-form-item>
                              <el-form-item label="目标表" prop="targetTable">
                                <el-select
                                  v-model="templetForms[index].targetTable"
                                  @change="targetTableChange($event, index)"
                                  placeholder="请选择"
                                >
                                  <template #prefix>
                                    <PieChart
                                      style="width: 1em; height: 1em; margin-right: 8px"
                                    ></PieChart>
                                  </template>
                                  <el-option
                                    v-for="item in targetTableOptions"
                                    :key="item.TABLE_NAME"
                                    COMMENTS
                                    :label="item.COMMENTS + '(' + item.TABLE_NAME + ')'"
                                    :value="item.TABLE_NAME"
                                  >
                                    <span style="float: left">
                                      <PieChart
                                        style="
                                          width: 1em;
                                          height: 1em;
                                          margin-right: 8px;
                                          margin-top: 10px;
                                        "
                                      ></PieChart
                                    ></span>
                                    <span style="padding-left: 6px"
                                      >{{ item.COMMENTS + '(' + item.TABLE_NAME + ')' }}
                                    </span>
                                  </el-option>
                                </el-select>
                              </el-form-item>
                              <el-form-item
                                label="目标表字段"
                                style="overflow: hidden; width: 100%; height: calc(100% - 140px)"
                              >
                                <vxe-table
                                  ref="xTable"
                                  border
                                  class="mytable-scrollbar"
                                  height="auto"
                                  align="center"
                                  :loading="modelsLoading"
                                  :data="templetForms[index].targetTableColumnData"
                                  :edit-config="{
                                    trigger: 'click',
                                    mode: 'cell',
                                    showStatus: true
                                  }"
                                  :row-config="{ isCurrent: true, isHover: true }"
                                  resizable
                                  show-overflow
                                  keep-source
                                  auto-resize
                                >
                                  <vxe-column type="seq" width="30"></vxe-column>
                                  <vxe-column
                                    field="columnName"
                                    title="字段编码"
                                    width="120"
                                  ></vxe-column>
                                  <vxe-column
                                    field="dataType"
                                    title="字段类型"
                                    width="100"
                                  ></vxe-column>
                                  <vxe-column
                                    field="comments"
                                    title="字段名称"
                                    width="120"
                                  ></vxe-column>
                                  <vxe-column
                                    field="pageColumn"
                                    title="页面字段"
                                    show-overflow
                                    width="490"
                                    :edit-render="{ autofocus: '.vxe-input--inner' }"
                                    align="left"
                                  >
                                    <template #edit="{ row }">
                                      <el-input
                                        type="textarea"
                                        :autosize="{ minRows: 1, maxRows: 4 }"
                                        placeholder="请设置模版内容"
                                        v-model="row.pageColumn"
                                        @click="handleInputBlur($event, index, row)"
                                      >
                                      </el-input>
                                    </template>
                                  </vxe-column>
                                </vxe-table>
                              </el-form-item>
                            </el-form>
                          </el-tab-pane>

                          <el-tab-pane
                            lazy
                            label="测试模式"
                            :disabled="templetForms[index].targetTable === ''"
                          >
                            <div class="formTableBox">
                              <div class="TestFormDiv">
                                <el-scrollbar>
                                  <el-form
                                    :model="testTabsFroms[index]"
                                    height="auto"
                                    max-width="875px"
                                    class="TestForm form-input-ml"
                                    :inline="true"
                                    :ref="'formTestDynamic' + index"
                                  >
                                    <el-form-item
                                      :label="p.chinaName"
                                      prop="p.chinaName"
                                      v-for="(p, pindex) in viewPageColumns"
                                      :key="pindex"
                                      class="testFormItem"
                                    >
                                      <el-input
                                        v-model="testTabsFroms[index][p.enName]"
                                        clearable
                                      ></el-input>
                                    </el-form-item>

                                    <el-form-item>
                                      <template #default>
                                        <el-button
                                          v-loading="submitLoading"
                                          icon="Check"
                                          @click="testTempletTodo(index)"
                                          class="button-blue"
                                          >提交</el-button
                                        >
                                      </template>
                                    </el-form-item>
                                    <el-form-item v-if="alertTag">
                                      <el-alert
                                        :title="errorAlert"
                                        :closable="false"
                                        :type="alertSuccessError == true ? 'success' : 'error'"
                                      />
                                    </el-form-item>
                                  </el-form>
                                </el-scrollbar>
                              </div>

                              <div class="modalTable">
                                <vxe-table
                                  border
                                  max-height="325px"
                                  class="mytable-scrollbar"
                                  align="center"
                                  ref="xTable1"
                                  :data="testTabsLists[index].testLists"
                                  :loading="testLoading"
                                  :row-config="{ isCurrent: true, isHover: true }"
                                  show-footer
                                  resizable
                                  show-overflow
                                  keep-source
                                  auto-resize
                                >
                                  <vxe-column type="seq" width="30"></vxe-column>
                                  <vxe-column
                                    field="USER_NAME"
                                    title="代办人姓名"
                                    width="120"
                                  ></vxe-column>
                                  <vxe-column
                                    field="TODO_TIME"
                                    title="创建时间"
                                    width="150"
                                  ></vxe-column>
                                  <vxe-column
                                    field="TITLE"
                                    title="任务标题"
                                    align="left"
                                    width="190"
                                  ></vxe-column>
                                  <vxe-column
                                    field="CONTENT"
                                    title="任务内容"
                                    align="left"
                                  ></vxe-column>
                                </vxe-table>
                              </div>
                            </div>
                          </el-tab-pane>
                        </el-tabs>
                      </el-card>
                    </div>
                  </div>
                  <el-empty :image-size="200" style="height: 100%" v-else />
                </el-scrollbar>
              </div>
            </Pane>

            <Pane>
              <el-scrollbar style="height: 100%">
                <div v-if="viewPageColumns.length > 0" class="pageColumns">
                  <el-row :gutter="10">
                    <el-col :span="12" v-for="(p, pindex) in viewPageColumns" :key="pindex">
                      <el-tooltip
                        class="item"
                        effect="dark"
                        placement="top-end"
                        :content="p.chinaName + '【' + p.enName + '】'"
                      >
                        <el-tag type="success" @click="insertPageColumn(p)">
                          {{ p.chinaName + '【' + p.enName + '】' }}
                        </el-tag>
                      </el-tooltip>
                    </el-col>
                  </el-row>
                </div>
                <el-empty :image-size="200" style="height: 100%" v-else />
              </el-scrollbar>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label="操作日志">
          <LogInfo requestUrl="/api/task/"></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </el-container>
  </div>
</template>
<script setup lang="ts">
// 引入组件区
import Breadcrumb from '@/components/Breadcrumb.vue';
import HomepageMenu from '@/components/HomePageMenu.vue';
import NoData from '@/components/NoData.vue'; //空状态
import LogInfo from '@/components/LogInfo.vue'; //日志
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { notifyType, notifyMessage } from '../../utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '../../stores/store';
let store = AppStore();
import type { FormInstance } from 'element-plus';
import { formatDateTime } from '@/utils/common'; //格式化时间

let showTreeLoading = ref(false); //左侧树加载状态
let modelsLoading = ref(false); //中间模版加载状态(设计模式)
let testLoading = ref(false); //中间模版加载状态(测试模式)
let submitLoading = ref(false); //测试模式里的提交按钮

// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let showTaskPageDialog = ref(false);
const taskPageFormRef = ref<FormInstance>(); //最左侧的弹框的form
const testFormDivRef = ref<FormInstance>(); //测试模式的动态form校验
let currentTreeId = ref(''); // 当前树选中行的id
let currentTreeNodes = reactive([]); // 当前树选中行
const moduleId = localStorage.getItem('moduleId');

let menuList: any = reactive([]);
let taskPageTree: any = reactive([]);
let defaultProps = reactive({
  children: 'children',
  label: 'name'
});
let taskTempletList: any = reactive([]);
let templetForms: any = reactive([]);
let taskPageForm = reactive({
  id: '',
  parentId: '',
  name: '',
  code: '',
  typeId: ''
});
// 校验规则
// 最左侧根模块
let addRouteDialogRules: any = {
  name: [
    {
      required: true,
      message: '请输入页面名称',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 256,
      message: '长度为1到256个字符',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入页面编号',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 256,
      message: '长度为1到256个字符',
      trigger: 'blur'
    },
    {
      message: '页面编号只能为数字或英文字母',
      trigger: 'blur',
      pattern: /^[a-zA-Z0-9]+$/
    }
  ],
  typeId: [
    {
      required: true,
      message: '请选择所属页面',
      trigger: 'change'
    }
  ]
};

// 中间模版设计模式
let modelDesignRules: any = {
  title: [
    {
      required: true,
      message: '请输入任务标题',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 256,
      message: '长度为1到256个字符',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入任务编码',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 256,
      message: '长度为1到256个字符',
      trigger: 'blur'
    },
    {
      message: '任务编码只能为数字或英文字母',
      trigger: 'blur',
      pattern: /^[a-zA-Z0-9]+$/
    }
  ],
  type: [
    {
      required: true,
      message: '请输入任务类型',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 256,
      message: '长度为1到256个字符',
      trigger: 'blur'
    }
  ],
  targetTable: [
    {
      required: true,
      message: '请选择目标表',
      trigger: 'change'
    }
  ]
};
let pageOptions: any = reactive([]);
let targetTableOptions: any = reactive([]);
let viewPageColumns: any = reactive([]);
let sltTaskPage: any = reactive({});
let cursorIndex: any = reactive({
  index: '',
  row: {}
});
let testTempletTodoItem = reactive([
  {
    title: '',
    code: '',
    id: ''
  }
]);
let testTabsLists = reactive([]);
let testTabsFroms: any = reactive([]);
let errorAlert = ref('测试提交任务状态'); //提交按钮提示的信息
let alertTag = ref(false); //提示信息的显示状态 默认不显示
let alertSuccessError = ref(false); //默认失败

// 方法定义区 =============
onMounted(() => {
  findTaskPageTree();
  findTableNames();
  getpageOptions();
  getMenuList();
  // adjustHeight()
});

// 测试预览
function testAdd(item: any, index: any) {
  alertTag.value = false;
  testTempletTodoItem[index] = item;
  let form = { pageCode: '', code: '', templetId: '' };
  viewPageColumns.forEach((item: any) => {
    form[item.enName] = '';
  });
  testTabsFroms[index] = form;
  testTabsLists[index] = {
    testLists: []
  };
  // 获取模版测试列表
  findTaskTempletTestList(item, index);
}

// 清空测试模式的form动态表单
function clearFrom(index: any) {
  Object.keys(testTabsFroms[index]).map((item) => (testTabsFroms[index][item] = ''));
}
// 测试数据插入
function testTempletTodo(index: any) {
  submitLoading.value = true;
  alertTag.value = false; //alert提示状态 没有提示
  alertSuccessError.value = false; //提示成功或者失败

  const url = '/api/task/public/pageInfoAddTransmitTodoTable';
  testTabsFroms[index].pageCode = sltTaskPage.code;
  testTabsFroms[index].code = testTempletTodoItem[index].code;
  testTabsFroms[index].title = testTempletTodoItem[index].title;
  testTabsFroms[index].templetId = testTempletTodoItem[index].id;
  proxy.$http
    .post(url, testTabsFroms[index])
    .then((res: any) => {
      if (res.status.code === 1) {
        alertSuccessError.value = true; //提示成功 绿色success
      } else {
        alertSuccessError.value = false; //提示失败 红色error
      }
      errorAlert.value = res.status.msg; //提示的消息
      alertTag.value = true; //alert提示显示状态 成功/失败一栏
      submitLoading.value = false;
      findTaskTempletTestList(testTempletTodoItem[index], index); //获取模版测试列表
      // 清空字段form表单
      clearFrom(index);
      setTimeout(() => {
        alertTag.value = false;
      }, 3000);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      submitLoading.value = false;
    });
  submitLoading.value = false;
}
// 获取菜单树型数据
function getMenuList() {
  // 通过权限信息获取菜单
  let moduleMenuMap = store.userInfo.moduleMenuMap;
  if (Object.keys(moduleMenuMap).includes(moduleId)) {
    menuList.push(...moduleMenuMap[moduleId]);
  }
}
// 获取所有界面字典
function getpageOptions() {
  const url = '/api/sys/basDict/findDictListByType';
  proxy.$http
    .get(url, { params: { code: 'znmb', grade: 0 } })
    .then((res: any) => {
      pageOptions.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取界面字段
function getPageColumns() {
  viewPageColumns.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { pid: sltTaskPage.typeId } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        // 设置界面字典
        viewPageColumns.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 获取页面列表
function findTaskPageTree() {
  showTreeLoading.value = true;
  taskPageTree.length = 0; //清空数据
  const url = '/api/task/page/getTaskPageListTree';
  proxy.$http
    .get(url)
    .then((res: any) => {
      taskPageTree.push(...res.data);
      if (taskPageTree.length > 0) {
        if (taskPageTree[0].children.length !== 0) {
          const firstId = taskPageTree[0].children[0].id; //选中的树id
          const selectNodes = taskPageTree[0].children[0]; //选中的树节点
          currentTreeId.value = firstId;
          currentTreeNodes = selectNodes;
        } else {
          const firstId = taskPageTree[0].id; //树id
          const selectNodes = taskPageTree[0]; //树节点
          currentTreeId.value = firstId;
          currentTreeNodes = selectNodes;
        }

        proxy.$nextTick(() => {
          proxy.$refs.leftTree.setCurrentKey(currentTreeId.value);
          handleNodeClick(currentTreeNodes);
        });
      }
      showTreeLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showTreeLoading.value = false;
    });
}
// 获取模版列表
function findTaskTempletList() {
  taskTempletList.length = 0;
  templetForms.length = 0;
  modelsLoading.value = true;
  const url = '/api/task/templet/findTaskTempletListByPageId/' + sltTaskPage.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      taskTempletList.push(...res.data);
      templetForms.push(...res.data);
      modelsLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      modelsLoading.value = false;
    });
}
// 获取模版测试列表
function findTaskTempletTestList(templet: any, index: any) {
  // testTableData[index].length = 0;
  testLoading.value = true;
  const url = '/api/task/templet/getTempletTestList/' + templet.targetTable + '/' + templet.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      res.data.forEach((item: any) => {
        return (
          (item.START_TIME = formatDateTime(item.START_TIME, 'yyyy-MM-dd hh:mm:ss')) &&
          (item.TODO_TIME = formatDateTime(item.TODO_TIME, 'yyyy-MM-dd hh:mm:ss'))
        );
      });
      testTabsLists[index].testLists = res.data;
      testLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      testLoading.value = false;
    });
}
// 获取目标表options
function findTableNames() {
  const url = '/api/task/public/findTableNames';
  proxy.$http
    .get(url)
    .then((res: any) => {
      targetTableOptions.push(...res.data);
    })
    .catch((err: any) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 获取目标表字段
function findTableColumns(tableName: any, index: any) {
  const url = '/api/task/public/findColumnsByTableName/' + tableName;
  proxy.$http
    .get(url)
    .then((res: any) => {
      templetForms[index].targetTableColumnData = res.data;
    })
    .catch((err: any) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 新增任务页面
function appendTaskPage(data: any) {
  taskPageForm.parentId = data.id;
  showTaskPageDialog.value = true;
}
// 添加根节点
function appendPPage() {
  taskPageForm.parentId = '0';
  showTaskPageDialog.value = true;
}

// 新建根模块的弹框取消
function closeTaskPageDialog(formLeft: any) {
  taskPageForm.parentId = '';
  (taskPageForm.id = ''),
    (taskPageForm.name = ''),
    (taskPageForm.code = ''),
    (taskPageForm.typeId = ''),
    (showTaskPageDialog.value = false);
  formLeft.resetFields(); //清空表单校验
}
// 编辑任务页面
function editTaskPage(item: any) {
  taskPageForm.parentId = item.parentId;
  taskPageForm.id = item.id;
  taskPageForm.name = item.name;
  taskPageForm.code = item.code;
  taskPageForm.typeId = item.typeId;
  showTaskPageDialog.value = true;
}

// 左侧弹框保存
function saveTaskPage(formLeft: any) {
  if (!formLeft) return;
  formLeft.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const taskPageObject = {
      id: taskPageForm.id,
      parentId: taskPageForm.parentId,
      orgId: '1',
      typeId: taskPageForm.typeId,
      name: taskPageForm.name,
      code: taskPageForm.code
    };
    let url = '';
    if (taskPageObject.id) {
      url = '/api/task/page/editTaskPage';
    } else {
      url = '/api/task/page/addTaskPage';
    }
    proxy.$http
      .post(url, taskPageObject)
      .then((res: any) => {
        if (res.status.code !== 1) {
          if (taskPageObject.id) {
            VxeMessage('保存失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
          // closeTaskPageDialog(formLeft)
        } else {
          if (taskPageObject.id) {
            VxeMessage('保存成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增成功', VxeNotifyType.success);
          }
          showTaskPageDialog.value = false;
          // 保存后清空表单
          closeTaskPageDialog(formLeft); //清空表单内容+校验+关闭弹框
        }
        // 重新获取数据
        findTaskPageTree(); //获取页面树
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
    return true;
  });
}
// 删除树节点
function removeTaskPage(row: any) {
  proxy
    .$confirm('确定删除此模块？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/task/page/deleteTaskPage';
      if (row.id) {
        if (row.children.length === 0) {
          proxy.$http.post(url, row).then((res: any) => {
            VxeMessage('删除模块成功', VxeNotifyType.success);
            findTaskPageTree();
          });
        } else {
          VxeMessage('该模块下存在子模块,不能删除', VxeNotifyType.error);
        }
      }
    });
}

// 点击树节点
function handleNodeClick(data: any) {
  viewPageColumns.length = 0;
  sltTaskPage = data;
  findTaskTempletList(); //获取模版列表
  // 父级不要获取界面字段
  // if (data.parentId !== '0') {
  getPageColumns(); //获取界面字段
  // }
}
function targetTableChange(item: any, index: any) {
  findTableColumns(item, index); //获取目标表字段
}
// 添加模版
function addFormList() {
  taskTempletList.length = taskTempletList.length + 1;
  let templetForm = {
    title: '',
    code: '',
    type: '',
    formula: '',
    targetTable: '',
    pageId: sltTaskPage.id,
    pageCode: sltTaskPage.code,
    targetTableColumnData: [],
    testTableData: []
  };
  templetForms.push(templetForm);
}

// 保存模版
function saveTemplet(index: any) {
  const indexform = proxy.$refs[`form${index}`][0];
  if (!indexform) return;
  indexform.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    let url = '';
    if (templetForms[index].id) {
      url = '/api/task/templet/editTaskTemplet';
    } else {
      url = '/api/task/templet/addTaskTemplet';
    }
    proxy.$http
      .post(url, templetForms[index])
      .then((res: any) => {
        if (res.status.code !== 1) {
          VxeMessage('修改模版失败', VxeNotifyType.error);
        } else {
          VxeMessage('修改模版成功', VxeNotifyType.success);
        }
        findTaskTempletList(); //重新获取模版列表
      })
      .catch((err: any) => {
        VxeMessage('修改模版异常', VxeNotifyType.error);
      });
    return true;
  });
}
// 删除模版
function removeTaskTemplet(row: any) {
  if (row === undefined || row === '' || row === null) {
    taskTempletList.length = taskTempletList.length - 1;
    VxeMessage('删除模版成功', VxeNotifyType.success);
  } else {
    proxy
      .$confirm('确定删除此模版？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const url = '/api/task/templet/deleteTaskTemplet';
        proxy.$http
          .post(url, row)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除模版成功', VxeNotifyType.success);
            } else {
              VxeMessage('删除模版失败', VxeNotifyType.error);
            }
            findTaskTempletList(); //重新获取模版列表
          })
          .catch((err: any) => {
            VxeMessage('删除模版异常', VxeNotifyType.error);
          });
      });
  }
}

// 判断弹框显示的标题
function titleType() {
  if (taskPageForm.id) {
    return `编辑`;
  } else {
    return `新建`;
  }
}
// 鼠标点击事件
function handleInputBlur(e, index, row) {
  cursorIndex.value = e.srcElement.selectionStart;
  cursorIndex.index = index;
  cursorIndex.row = row;
}
// 在鼠标点击位置插入字段值
function insertPageColumn(tag) {
  if (cursorIndex.value) {
    let datas = templetForms[cursorIndex.index].targetTableColumnData;
    let row = datas.find((item) => item.columnName === cursorIndex.row.columnName);
    let pageColumnStr = row.pageColumn + '';
    let resultPageColumnStr = '';
    if (pageColumnStr.length <= cursorIndex.value) {
      resultPageColumnStr = pageColumnStr + '{' + tag.enName + '}';
    } else {
      let s1 = pageColumnStr.substring(0, cursorIndex.value);
      let s2 = pageColumnStr.substring(cursorIndex.value, pageColumnStr.length);
      resultPageColumnStr = s1 + '{' + tag.enName + '}' + s2;
    }
    templetForms[cursorIndex.index].targetTableColumnData.map((item) => {
      if (item.columnName == row.columnName) {
        item.pageColumn = resultPageColumnStr;
      }
      return item;
    });
  }
}
</script>
<style lang="scss" scoped>
#TaskTempletList {
  width: 100%;
  height: calc(100% - 56px);
  // 卡片下的阴影
  .el-card.is-always-shadow {
    box-shadow: none;
  }
  // 滚动条的位置
  :deep(.el-scrollbar__bar) {
    right: 4px !important;
  }
  // 空状态的位置
  :deep(.el-scrollbar__view) {
    height: 100%;
    .el-empty__description {
      margin-top: 5px;
    }
  }
  // vxe-table 目标表最后一个字段/两个字段左间距5px
  :deep(.vxe-table--render-default .col--left) {
    .vxe-cell {
      padding-left: 5px;
    }
  }

  // 整个内容盒子布局
  .bodyContent {
    height: calc(100% - 40px);
    .el-tabs {
      width: 100%;
      height: 100%;
      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0;
        // 传输模版 操作日志
        #pane-0,
        #pane-1 {
          height: 100%;
        }
      }
    }
  }

  .splitpanes {
    .splitpanes__pane {
      background-color: $base-white;
      // 最左侧新增根模块
      .addRootBtn {
        margin: 10px 10px 0 10px !important;
      }
      // 最左侧的树
      .sampleType {
        height: 100%;
        // el-tree
        .tools-tree {
          min-width: 168px;
          padding: 5px;
          font-size: $font-size;
          border: none;
          .cirBtn {
            display: none;
            width: 16px;
            height: 16px;
            padding: 0px;
            margin-left: 10px;
          }
          .el-tree-node__content:hover {
            .cirBtn {
              display: inline-block !important;
            }
          }
        }
      }
      // 中间区域
      .models {
        height: 100%;
        //中间新增模版
        .addModels {
          margin: 10px !important;
        }
        :deep(.el-scrollbar) {
          padding: 0 10px 0 10px;
        }
        .MiddleContent {
          height: 100%;
          .cardBox {
            margin-bottom: 10px;
            &:last-child {
              margin-bottom: 0;
            }
            // 数据传输模版卡片
            .box-card {
              // 卡片里的内边距
              :deep(.el-card__body) {
                padding: 0;
                .el-tabs--border-card {
                  border: none;
                }
              }

              :deep(.el-tabs__content) {
                padding: 5px 15px 15px 15px;
                &:last-child {
                  padding: 5px 15px 10px 15px;
                }
                #pane-0 {
                  height: 100%;
                  .el-form {
                    height: calc(100% - 41px);
                  }
                }
              }
              // 卡片头部按钮区域
              .card_header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                span {
                  font-size: $font-size-m;
                  padding: 10px;
                }
              }

              // form表单里每一个table的行高度
              :deep(.vxe-body--row) {
                height: 40px;
              }
              // 可拖拉文本域
              .el-textarea {
                margin-top: -3px;
              }
            }
          }
        }
      }
      .TestFormDiv {
        overflow: hidden;
        width: 100%;
        // 测试预览的form表单
        .TestForm {
          display: flex;
          flex-wrap: wrap;
          .testFormItem {
            &:nth-child(1) {
              margin-top: 10px;
            }
            &:nth-child(2) {
              margin-top: 10px;
            }
            width: 40%;
            align-items: center;
            justify-content: center;
          }
          // 提交的alert提示
          .el-alert {
            width: 770px;
            margin-left: 42px;
            height: 32px;
          }
        }
      }

      // 测试预览的table
      .modalTable {
        overflow: hidden;
        width: 100%;
        // form表单里每一个table的行高度
        :deep(.vxe-body--row) {
          height: 30px !important;
        }
      }

      // 最右侧的tag显示
      .pageColumns {
        width: calc(100% - 10px);
        height: calc(100% - 20px);
        padding: 10px 0 10px 10px;
        .el-row {
          width: calc(100% - 10px);
          margin-left: 0 !important;
          margin-right: 0 !important;
          .el-tag {
            width: 100%;
            text-align: left;
            padding: 15px 15px 15px 10px;
            margin-bottom: 10px;
            font-size: $font-size;
            min-width: 225px;
            justify-content: flex-start;

            :deep(.el-tag__content) {
              white-space: nowrap; // 禁止文本换行
              overflow: hidden; // 隐藏溢出的文本
              text-overflow: ellipsis; // 使用省略号来代替溢出的文本
            }
          }
        }
      }
    }
  }
}
</style>
